package com.wanmait.jd.controller;

import com.wanmait.jd.dao.UserinfoDAO;
import com.wanmait.jd.vo.Userinfo;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


@Controller
public class RegisterController {
    @GetMapping("isRename")
    @ResponseBody //不转发
    public String isRename(String x){
        UserinfoDAO userinfoDAO = new UserinfoDAO();
        Userinfo userinfo = userinfoDAO.findByUsername(x);
        if (userinfo==null){//不重复
            return "1";
        }else {//重复
            return "0";
        }
    }

    @RequestMapping("register")
    public String register(Userinfo userinfo, HttpServletRequest request,MultipartFile face){
        if (!face.isEmpty()){
            //face--uploadImage
            String filepath = request.getServletContext().getRealPath("/uploadImage");//文件夹绝对路径
            //获取原文件的扩展名
            String originalFilename = face.getOriginalFilename();
            //jar
            String filenameUtils = FilenameUtils.getExtension(originalFilename);
            //新文件名
            String filename = UUID.randomUUID().toString()+"."+filenameUtils;
            userinfo.setUserface(filename);
            try {
                face.transferTo(new File(filepath+"/"+filename));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        UserinfoDAO userinfoDAO = new UserinfoDAO();
        userinfoDAO.insert(userinfo);

        return "redirect:/R/enter.jsp";
    }
}
